package controllers

import (
	"errors"
	"slotGame/models"
	"slotGame/utils"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/astaxie/beego"
)

var (
	_addCoinPrizePoolSync sync.Mutex // 奖池金额操作 互斥锁
)

// PrizePoolController oprations for PrizePool
type PrizePoolController struct {
	beego.Controller
}

// 判断当前 游戏得分模式
func GetScoreMode() (result int) {
	result = models.USERMODE_EAT // 吃分模式
	// 奖池阀值
	pp := models.PrizePool{Id: 1}
	err := pp.Read("coin")
	if err != nil {
		beego.Error(err)
		return
	}
	if pp.Coin > GetComparesection() { // 奖池 超过 奖池阀值
		result = models.USERMODE_SPIT // 吐分模式
	}
	return
}

// 增加 或 减少 奖池金额
func AddCoinPrizePool(add_coin float64) error {
	_addCoinPrizePoolSync.Lock()
	defer _addCoinPrizePoolSync.Unlock()

	pp := models.PrizePool{Id: 1}
	err := pp.Read()
	if err != nil {
		beego.Error(err)
		return err
	}
	pp.Coin += add_coin
	_, err = pp.Update()
	return err

}

// GetPrizePool ...
// @Title Get One PrizePool
// @Description get PrizePool by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.PrizePool
// @Failure 403 :id is empty
// @router /:id [get]
func (c *PrizePoolController) GetPrizePool() {
	idStr := c.Ctx.Input.Param(":id")
	id, _ := strconv.Atoi(idStr)
	v := models.PrizePool{Id: id}
	err := v.Read()
	if err != nil {
		c.Data["json"] = err.Error()
	} else {
		c.Data["json"] = v
	}
	c.ServeJSON()
}

// AddPrizePool ...
// @Title Add PrizePool
// @Description 初始化奖池、奖池金额增加和减少
// @Param	coin		path 	string	true		"奖池增加或减少的金额"
// @Param	note		path 	string	true		"备注"
// @Success 200 {object} models.PrizePool
// @Failure 403 :coin is empty
// @router /:coin/:note [get]
func (c *PrizePoolController) AddPrizePool() {
	coin_str_ := c.Ctx.Input.Param(":coin")
	coin_num_, err := strconv.ParseFloat(coin_str_, 10)
	if err != nil {
		c.Data["json"] = utils.Reponse(403, nil, "输入金额无效", "输入金额无效："+coin_str_)
		c.ServeJSON()
		return
	}

	v := models.PrizePool{Id: 1}
	err = v.Read()
	first := false
	if err != nil { // 当奖池金额不存在就按照第一条记录创建
		if err.Error() == "<QuerySeter> no row found" && coin_num_ >= 0 {
			v.Coin = float64(coin_num_)
			v.CreateTime = time.Now()
			v.Insert()
			first = true
		} else {
			c.Data["json"] = err.Error()
			c.ServeJSON()
			return
		}
	}
	if !first {
		v.Coin += float64(coin_num_)
	}
	if _, err = v.Update(); err != nil {
		c.Data["json"] = err.Error()
		c.ServeJSON()
		return
	}
	c.Data["json"] = v

	v = models.PrizePool{Coin: float64(coin_num_), CreateTime: time.Now(), Note: c.Ctx.Input.Param(":note")}
	v.Insert()
	c.ServeJSON()
}

// GetAll ...
// @Title Get All
// @Description get PrizePool
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.PrizePool
// @Failure 403
// @router / [get]
func (c *PrizePoolController) GetAll() {
	var fields []string
	var sortby []string
	var order []string
	var query = make(map[string]string)
	var limit int64 = 10
	var offset int64

	// fields: col1,col2,entity.col3
	if v := c.GetString("fields"); v != "" {
		fields = strings.Split(v, ",")
	}
	// limit: 10 (default is 10)
	if v, err := c.GetInt64("limit"); err == nil {
		limit = v
	}
	// offset: 0 (default is 0)
	if v, err := c.GetInt64("offset"); err == nil {
		offset = v
	}
	// sortby: col1,col2
	if v := c.GetString("sortby"); v != "" {
		sortby = strings.Split(v, ",")
	}
	// order: desc,asc
	if v := c.GetString("order"); v != "" {
		order = strings.Split(v, ",")
	}
	// query: k:v,k:v
	if v := c.GetString("query"); v != "" {
		for _, cond := range strings.Split(v, ",") {
			kv := strings.SplitN(cond, ":", 2)
			if len(kv) != 2 {
				c.Data["json"] = errors.New("Error: invalid query key/value pair")
				c.ServeJSON()
				return
			}
			k, v := kv[0], kv[1]
			query[k] = v
		}
	}

	l, err := models.GetAllPrizePool(query, fields, sortby, order, offset, limit)
	if err != nil {
		c.Data["json"] = err.Error()
	} else {
		c.Data["json"] = l
	}
	c.ServeJSON()
}
